package com.xindaoapp.happypet.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.adapter.MyPostListAdapter2.OnNextPageListener;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData;
import com.xindaoapp.happypet.bean.MainZuixinData;
import com.xindaoapp.happypet.bean.Message;
import com.xindaoapp.happypet.bean.PostListEntity;
import com.xindaoapp.happypet.bean.PostListEntity.ForumInfo;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.ui.ClubDetailActivity;
import com.xindaoapp.happypet.ui.PostDetailImgsActivity;
import com.xindaoapp.happypet.ui.PostMessageActivity;
import com.xindaoapp.happypet.ui.ZanListActivity;
import com.xindaoapp.happypet.utils.BitmapUtil;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.ProgressHUD;
import com.xindaoapp.happypet.utils.xdConfig;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.FilterPopupWindow;

/**
 * 圈子列表页
 * 
 * @author Yangqing
 * 
 */
public class MyClubActivity extends BaseLoadAnimationAcitivity implements OnClickListener {
    @SuppressWarnings("unused")
    private final String TAG = "MyClubActivity";
    // private RelativeLayout no_data;
    private ImageButton cancle;
    private TextView tv_title;
    private ImageButton post;
    private TextView tab_1;
    private TextView tab_2;
    private TextView tab_4;

    private PullToRefreshListView listView1;
    private int currentIndex = 1;
    private int oldIndex = 1;
    private boolean refresh = false;
    private boolean loadMore = false;

    private Activity context;
    private String name;
    private String fId;
    private String filter = "lastpost";

    private final int pageNum1 = 1;
    private final int pageNum2 = 1;
    private final int pageNum3 = 1;
    private final int pageNum4 = 1;

    private final int totalCount1 = 0;
    private final int totalCount2 = 0;
    private final int totalCount3 = 0;
    private final int totalCount4 = 0;
    private final int[] pageNums = {pageNum1, pageNum2, pageNum3, pageNum4};
    private final int[] totalCounts = {totalCount1, totalCount2, totalCount3, totalCount4};

    private MyClubBroadCast mZanHuifubroadCast;

    private MyBroadcastReciver mMyBroadcastReciver;



    private RelativeLayout noresult;

    private boolean b1 = true;
    private boolean b2 = true;
    private boolean b3 = true;
    private boolean b4 = true;

    private PostMessageBroadcast mPostMessageBroadcast;
    private LoginSuccessBroadRevicer mLoginSuccessBroadRevicer;
    private CircleImageView quanzi_icon;// 圈子logo
    private TextView tv_tuangroup, tv_quanname;// 圈名称、团成员
    private ImageView iv_addquanzi;// 加入圈子
    private ForumInfo mForumInfo;// 论坛信息
    private View quanzi_top;
    private FilterPopupWindow filterPopupWin;
    private View rl_rl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_club);
        super.onCreate(savedInstanceState);
        context = MyClubActivity.this;
        name = getIntent().getStringExtra("name");
        fId = getIntent().getStringExtra("fId");

        initView();
        initData();
        mPostMessageBroadcast = new PostMessageBroadcast();
        mZanHuifubroadCast = new MyClubBroadCast();
        registerReceiver(mPostMessageBroadcast, new IntentFilter(Constants.ACTION_POST_SUCCESS));
        registerReceiver(mZanHuifubroadCast, new IntentFilter(Constants.ACTION_REPLAY_SUCCESS));
        registerReceiver(mLoginSuccessBroadRevicer = new LoginSuccessBroadRevicer(),
                new IntentFilter(Constants.ACTION_LOGIN_STATE_CHANGED));
        this.registerReceiver(mMyBroadcastReciver = new MyBroadcastReciver(), new IntentFilter(
                Constants.KEY_SEND_POST_SUCCESS));


    }

    /** 初始化圈子信息 */
    private void initQuanziInfo() {
        if (mForumInfo != null) {
            if (quanzi_icon != null)
                ImageLoader.getInstance().displayImage(mForumInfo.ico, quanzi_icon);
            if (tv_quanname != null)
                tv_quanname.setText("圈   主:" + mForumInfo.moderators);
            if (tv_tuangroup != null)
                tv_tuangroup.setText("圈成员:" + mForumInfo.membernum);
            if ("1".equals(mForumInfo.isjoin))
                Constants.ISMYGROUP = true;
            else
                Constants.ISMYGROUP = false;
            changeTopBarState();

        }
    }

    private class MyBroadcastReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            getData(fId);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        changeTopBarState();
    }

    private void initView() {
        // no_data = (RelativeLayout) findViewById(R.id.no_data);
        cancle = (ImageButton) findViewById(R.id.cancel);
        tv_title = (TextView) findViewById(R.id.check_club);
        post = (ImageButton) findViewById(R.id.publish);
        noresult = (RelativeLayout) findViewById(R.id.noresult);
        rl_rl = findViewById(R.id.rl_rl);


        cancle.setOnClickListener(this);

        tv_title.setText(name.replace("俱乐部", ""));

        listView1 = (PullToRefreshListView) findViewById(R.id.listview1);
        listView1.setMode(Mode.PULL_FROM_START);


        quanzi_top = View.inflate(this, R.layout.item_quanzi_top, null);
        quanzi_icon = (CircleImageView) quanzi_top.findViewById(R.id.quanzi_icon);
        tv_quanname = (TextView) quanzi_top.findViewById(R.id.tv_quanname);
        tv_tuangroup = (TextView) quanzi_top.findViewById(R.id.tv_tuangroup);
        iv_addquanzi = (ImageView) quanzi_top.findViewById(R.id.iv_addquanzi);
        ll_title_bar = (LinearLayout) quanzi_top.findViewById(R.id.ll_ll);
        // loading = (FrameLayout) quanzi_top.findViewById(R.id.include_loading);
        initQuanziTopClick();
        changeTopBarState();

        tab_1 = (TextView) quanzi_top.findViewById(R.id.tab_1);
        tab_2 = (TextView) quanzi_top.findViewById(R.id.tab_2);
        tab_4 = (TextView) quanzi_top.findViewById(R.id.tab_4);


        if (listView1.getRefreshableView().getHeaderViewsCount() <= 1)
            listView1.getRefreshableView().addHeaderView(quanzi_top);

        listView1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Message post = (Message) parent.getAdapter().getItem(position);

                if (post != null) {
                    Intent intent =
                            new Intent(getBaseContext(),
                                    com.xindaoapp.happypet.ui.PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, post.tid);
                    intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                    intent.putExtra(Constants.KEY_POST_FROM_POSTLIST, true);
                    startActivity(intent);
                }

            }
        });

    }

    private void changeTopBarState() {
        if (Constants.ISMYGROUP) {
            quanzi_top.setClickable(true);
            iv_addquanzi.setBackgroundResource(R.drawable.post_arraw);
        } else {
            quanzi_top.setClickable(false);
            iv_addquanzi.setBackgroundResource(R.drawable.post_add);
        }
    }

    private void initQuanziTopClick() {
        // 跳转圈子详情
        quanzi_top.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyClubActivity.this, ClubDetailActivity.class);
                intent.putExtra("name", name);
                intent.putExtra("forumInfo", mForumInfo);
                startActivity(intent);
            }
        });
    }

    private void initData() {
        getData(fId);
        listView1.setOnRefreshListener(new OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getRefreshData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageNums[currentIndex - 1]++;
                refresh = false;
                loadMore = true;
                int limit = xdConfig.PAGE_SIZE;
                if ((pageNums[0] - 1) * limit > totalCounts[currentIndex - 1]) {
                    listView1.onRefreshComplete();
                    return;
                }
                getData(fId);
            }
        });

    }

    /**
     * 初始化选择的头部
     */
    private void initSelectTitle() {
        ll_title_bar.setBackgroundResource(R.drawable.post_tab01);
        tab_1.setTextColor(getResources().getColor(R.color.red));
        tab_2.setTextColor(getResources().getColor(R.color.red));
        tab_4.setTextColor(getResources().getColor(R.color.red));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab_1:
                if (currentIndex == 1) {
                    return;
                }
                // no_data.setVisibility(View.GONE);
                currentIndex = 1;
                initSelectTitle();
                tab_1.setTextColor(getResources().getColor(R.color.white));
                filter = "lastpost";// 最新

                // loading();
                getData(fId);
                break;
            case R.id.tab_2:
                if (currentIndex == 2) {
                    return;
                }
                // no_data.setVisibility(View.GONE);
                currentIndex = 2;
                initSelectTitle();
                tab_2.setTextColor(getResources().getColor(R.color.white));
                ll_title_bar.setBackgroundResource(R.drawable.post_tab02);

                filter = "digest";

                // loading();
                getData(fId);
                break;
            case R.id.tab_3:
                if (currentIndex == 3) {
                    return;
                }
                // no_data.setVisibility(View.GONE);
                currentIndex = 3;


                filter = "";
                listView1.setVisibility(View.GONE);
                getData(fId);
                break;
            case R.id.tab_4:
                if (currentIndex == 4) {
                    return;
                }
                // no_data.setVisibility(View.GONE);
                currentIndex = 4;
                initSelectTitle();
                tab_4.setTextColor(getResources().getColor(R.color.white));
                ll_title_bar.setBackgroundResource(R.drawable.post_tab04);
                filter = "petvideo";

                // loading();
                getData(fId);
                break;
            case R.id.cancel:
                finish();
                break;
            case R.id.publish:
                if (UserState.isLogged(context)) {
                    if (mForumInfo != null) {
                        Intent intent = new Intent(getBaseContext(), PostMessageActivity.class);
                        intent.putExtra(Constants.KEY_GROUP_NAME, mForumInfo.name);
                        intent.putExtra(Constants.KEY_GROUP_MEMBER, mForumInfo.membernum);
                        intent.putExtra(Constants.KEY_GROUP_ICON, mForumInfo.ico);
                        intent.putExtra(Constants.KEY_GROUP_FID, mForumInfo.fid);
                        startActivityForResult(intent, Constants.REQUESTCODE_POSTED);
                    }

                    // 添加动画
                    // overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
                    overridePendingTransition(R.anim.new_dync_in_from_right,
                            R.anim.new_dync_out_to_left);
                }
                break;

            case R.id.iv_addquanzi:// 添加到圈子
                if (Constants.ISMYGROUP) {// 进入圈子详情查看
                    Intent intent = new Intent(MyClubActivity.this, ClubDetailActivity.class);
                    intent.putExtra("forumInfo", mForumInfo);
                    intent.putExtra("name", mForumInfo.name);
                    startActivity(intent);
                } else {// 加入圈子
                    if (UserState.isLogged(MyClubActivity.this)) {
                        if (UserState.isLogged(MyClubActivity.this)) {
                            final ProgressHUD ProgressDialog =
                                    ProgressHUD.show(MyClubActivity.this, "正在加载...", true, true,
                                            null);
                            getMoccaApi().joinGroup(fId, MyClubActivity.this,
                                    new IRequest<Boolean>() {
                                        @Override
                                        public void request(Boolean t) {
                                            if (null != ProgressDialog
                                                    && ProgressDialog.isShowing()) {
                                                ProgressDialog.dismiss();
                                            }
                                            if (t) {
                                                Constants.ISMYGROUP = true;
                                                quanzi_top.setClickable(true);
                                                iv_addquanzi
                                                        .setBackgroundResource(R.drawable.post_arraw);
                                            } else {
                                                Constants.ISMYGROUP = false;
                                                quanzi_top.setClickable(false);
                                            }
                                            sendBroadcast(new Intent(Constants.JOIN_OUT_GROUP));
                                        }
                                    });
                        } else {
                            Toast.makeText(getApplicationContext(), R.string.pLease_check_network,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                }
                break;
            case R.id.check_club:
                // case R.id.home_tittle_img:// 显示标题部分筛选
                // getPopupWindow();
                // break;
            default:
                break;
        }
    }

    /**
     * 顶部筛选
     */
    private void getPopupWindow() {
        filterPopupWin = new FilterPopupWindow(context, itemsClick);
        filterPopupWin.showAsDropDown(rl_rl,
                (CommonParameter.sScreenWidth - tv_title.getWidth()) / 2, 0);
    }

    private final OnClickListener itemsClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_new:// 最新
                    filter = "lastpost";
                    loading();
                    getData(fId);
                    break;
                case R.id.btn_hot:// 最热
                    filter = "heat";
                    loading();
                    getData(fId);
                    break;
            }
            filterPopupWin.dismiss();
        }
    };
    private LinearLayout ll_title_bar;

    private void getData(String fid) {

        if (noresult.getVisibility() == View.VISIBLE) {
            noresult.setVisibility(View.GONE);
        }
        if (CommonUtil.checkNetState(context)) {
            // no_data.setVisibility(View.GONE);
            final RequestParams params = new RequestParams();
            params.put("page", String.valueOf(pageNums[currentIndex - 1]));
            params.put("pagesize", xdConfig.PAGE_SIZE + "");
            params.put("fid", getIntent().getStringExtra("fId"));
            params.put("filter", filter);
            // final ProgressHUD progressHUD = ProgressHUD.show(context, "正在加载...", true, true,
            // null);
            XDHttpClient.get(xdConfig.THREADLIST, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, String content) {
                    initEventsByLoadData();
                    onDataArrived(true);
                    List<Message> list1 = new ArrayList<Message>();
                    if (noresult.getVisibility() == View.VISIBLE) {
                        noresult.setVisibility(View.GONE);
                    }
                    listView1.onRefreshComplete();
                    if (TextUtils.isEmpty(content)) {
                        return;
                    }

                    PostListEntity entity = null;
                    try {
                        entity = JSON.parseObject(content, PostListEntity.class);
                        list1 =
                                JSON.parseArray(JSON.parseObject(content).getJSONArray("array")
                                        .toJSONString(), Message.class);
                    } catch (Exception e) {
                    }

                    if (null == entity) {
                        Toast.makeText(context, R.string.get_error_data, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (entity.foruminfo != null && !TextUtils.isEmpty(entity.foruminfo.fid)) {
                        mForumInfo = entity.foruminfo;
                        initQuanziInfo();
                    }
                    switch (currentIndex) {
                        case 1:
                            b1 = false;
                            totalCounts[currentIndex - 1] = Integer.parseInt(entity.getTotal());
                            // MyPostListAdapter2 mAdapter1 =
                            // new MyPostListAdapter2(MyClubActivity.this, list1,
                            // Constants.PAGE_SIZE, R.layout.activity_my_club_item,
                            // R.layout.item_loading);
                            // mAdapter1.setOnNextPageListener(onNextPageListener);
                            MyClubAdapter mAdapter1 =
                                    new MyClubAdapter(context, list1, Constants.PAGE_SIZE,
                                            R.layout.item_zuixinfragment, R.layout.item_loading);
                            listView1.getRefreshableView().setAdapter(mAdapter1);
                            oldIndex = 1;
                            break;
                        case 2:
                            b2 = false;
                            totalCounts[currentIndex - 1] = Integer.parseInt(entity.getTotal());
                            // MyPostListAdapter2 mAdapter2 =
                            // new MyPostListAdapter2(MyClubActivity.this, list1,
                            // Constants.PAGE_SIZE, R.layout.activity_my_club_item,
                            // R.layout.item_loading);
                            // mAdapter2.setOnNextPageListener(onNextPageListener);
                            MyClubAdapter mAdapter2 =
                                    new MyClubAdapter(context, list1, Constants.PAGE_SIZE,
                                            R.layout.item_zuixinfragment, R.layout.item_loading);
                            listView1.getRefreshableView().setAdapter(mAdapter2);
                            oldIndex = 2;
                            break;
                        case 3:
                            b3 = false;
                            totalCounts[currentIndex - 1] = Integer.parseInt(entity.getTotal());
                            // MyPostListAdapter2 mAdapter3 =
                            // new MyPostListAdapter2(MyClubActivity.this, list1,
                            // Constants.PAGE_SIZE, R.layout.activity_my_club_item,
                            // R.layout.item_loading);
                            // mAdapter3.setOnNextPageListener(onNextPageListener);
                            MyClubAdapter mAdapter3 =
                                    new MyClubAdapter(context, list1, Constants.PAGE_SIZE,
                                            R.layout.item_zuixinfragment, R.layout.item_loading);
                            listView1.getRefreshableView().setAdapter(mAdapter3);
                            oldIndex = 3;
                            break;
                        case 4:
                            b4 = false;
                            totalCounts[currentIndex - 1] = Integer.parseInt(entity.getTotal());
                            // MyPostListAdapter2 mAdapter4 =
                            // new MyPostListAdapter2(MyClubActivity.this, list1,
                            // Constants.PAGE_SIZE, R.layout.activity_my_club_item,
                            // R.layout.item_loading);
                            // mAdapter4.setOnNextPageListener(onNextPageListener);
                            MyClubAdapter mAdapter4 =
                                    new MyClubAdapter(context, list1, Constants.PAGE_SIZE,
                                            R.layout.item_zuixinfragment, R.layout.item_loading);
                            listView1.getRefreshableView().setAdapter(mAdapter4);
                            oldIndex = 4;
                            break;

                        default:
                            break;
                    }
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    // Toast.makeText(context, R.string.get_error_data, 0).show();
                    switch (currentIndex) {
                        case 1:
                            if (b1) {
                                onDataArrived(false);
                                SetOnLoadFailListener(new OnLoadFailListener() {
                                    @Override
                                    public void onLoadFail() {
                                        getData(fId);
                                    }
                                });
                            } else {
                                onDataArrived(true);
                            }
                            break;
                        case 2:
                            if (b2) {
                                onDataArrived(false);
                                SetOnLoadFailListener(new OnLoadFailListener() {
                                    @Override
                                    public void onLoadFail() {
                                        getData(fId);
                                    }
                                });
                            } else {
                                onDataArrived(true);
                            }
                            break;
                        case 3:
                            if (b3) {
                                onDataArrived(false);
                                SetOnLoadFailListener(new OnLoadFailListener() {
                                    @Override
                                    public void onLoadFail() {
                                        getData(fId);
                                    }
                                });
                            } else {
                                onDataArrived(true);
                            }
                            break;
                        case 4:
                            if (b4) {
                                onDataArrived(false);
                                SetOnLoadFailListener(new OnLoadFailListener() {
                                    @Override
                                    public void onLoadFail() {
                                        getData(fId);
                                    }
                                });
                            } else {
                                onDataArrived(true);
                            }
                            break;

                        default:
                            break;
                    }
                }

            });

        } else {// 提示网络未连接
            Toast.makeText(context, R.string.pLease_check_network, Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 在加载成功后，初始化点击事件
     */
    protected void initEventsByLoadData() {
        tab_1.setOnClickListener(this);
        tab_2.setOnClickListener(this);
        tab_4.setOnClickListener(this);
        iv_addquanzi.setOnClickListener(this);
        post.setOnClickListener(this);
        tv_title.setOnClickListener(this);
    }

    /**
     * 加載下一頁的方法
     */
    private final OnNextPageListener onNextPageListener = new OnNextPageListener() {

        @Override
        public void nextPage(int start, int size, final ILoadNextPageData<Message> iLoadNextPageData) {
            final RequestParams params = new RequestParams();
            params.put("page", String.valueOf(start));
            params.put("pagesize", String.valueOf(size));
            params.put("fid", fId);
            params.put("filter", filter);
            XDHttpClient.get(xdConfig.THREADLIST, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, String content) {
                    List<Message> message =
                            JSON.parseArray(JSON.parseObject(content).getJSONArray("array")
                                    .toJSONString(), Message.class);
                    iLoadNextPageData.loadNextPageData(message);
                }
            });
        }
    };


    private View mBackToTop;

    @Override
    protected void onDestroy() {
        unregisterReceiver(mPostMessageBroadcast);
        unregisterReceiver(mZanHuifubroadCast);
        unregisterReceiver(mMyBroadcastReciver);
        unregisterReceiver(mLoginSuccessBroadRevicer);

        super.onDestroy();
    }

    private void getRefreshData() {
        pageNums[currentIndex - 1] = 1;
        refresh = true;
        loadMore = false;
        getData(fId);
    }

    /**
     * 接收到发帖成功的广播
     * 
     * @author chenghao
     */
    class PostMessageBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 重新刷新列表页面
            getRefreshData();
        }
    }

    private class MyClubBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            getRefreshData();
        }

    }
    private class LoginSuccessBroadRevicer extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            getData(fId);
        }

    }

    //
    public class MyClubAdapter extends XinDaoBaseAdapter<Message> {
        Map<Integer, ImageView> map = new HashMap<Integer, ImageView>();
        Map<Integer, Boolean> isZanMap = new HashMap<Integer, Boolean>();

        public MyClubAdapter(Context context, List<Message> iniData, int pageSize, int res,
                int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        protected List<Message> parseResult(List<Message> list) {
            // TODO Auto-generated method stub
            for (int i = list.size() - 1; i >= 0; i--) {
                if (getResult().contains(list.get(i))) {
                    list.remove(list.get(i));
                }
            }
            return list;
        }

        // 需要重写
        @Override
        public void nextPage(int start, int size, final ILoadNextPageData<Message> iLoadNextPageData) {
            super.nextPage(start, size, iLoadNextPageData);

            final RequestParams params = new RequestParams();
            params.put("page", String.valueOf(start));
            params.put("pagesize", String.valueOf(size));
            params.put("fid", fId);
            params.put("filter", filter);
            XDHttpClient.get(xdConfig.THREADLIST, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, String content) {
                    List<Message> message =
                            JSON.parseArray(JSON.parseObject(content).getJSONArray("array")
                                    .toJSONString(), Message.class);
                    iLoadNextPageData.loadNextPageData(message);
                }
            });


        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent,
                final Message value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();

            if (holder == null) {
                holder = new ViewHolder();
                holder.line = convertView.findViewById(R.id.line);
                holder.layout_imgs = (LinearLayout) convertView.findViewById(R.id.layout_imgs);
                holder.lay_zan = (RelativeLayout) convertView.findViewById(R.id.lay_zan);
                holder.layout_gozan = (RelativeLayout) convertView.findViewById(R.id.layout_gozan);
                holder.layout_gohuifu =
                        (RelativeLayout) convertView.findViewById(R.id.layout_gohuifu);
                holder.iv_icon = (CircleImageView) convertView.findViewById(R.id.iv_icon);
                holder.iv_zan = (ImageView) convertView.findViewById(R.id.iv_zan);
                holder.iv_jing = (ImageView) convertView.findViewById(R.id.iv_jing);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
                holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
                holder.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
                holder.tv_position = (TextView) convertView.findViewById(R.id.tv_position);
                holder.tv_views = (TextView) convertView.findViewById(R.id.tv_viewcount);
                holder.tv_zancount = (TextView) convertView.findViewById(R.id.tv_zancount);
                holder.tv_huifucount = (TextView) convertView.findViewById(R.id.tv_huifucount);
                holder.tv_zanname1 = (TextView) convertView.findViewById(R.id.tv_zanname1);
                holder.tv_zanname2 = (TextView) convertView.findViewById(R.id.tv_zanname2);
                holder.tv_zanguo = (TextView) convertView.findViewById(R.id.tv_zanguo);
                convertView.setTag(holder);
            }

            map.put(position, holder.iv_zan);

            holder.tv_views.setText(value.views);

            if (value != null
                    && Integer.parseInt(TextUtils.isEmpty(value.recommend_add) ? "0"
                            : value.recommend_add) > 0) {
                holder.tv_zancount.setText(value.recommend_add);
            } else {
                holder.tv_zancount.setText("赞");
            }

            holder.tv_huifucount.setText(value.replies);


            ImageLoader.getInstance().displayImage(value.userface, holder.iv_icon,
                    BitmapUtil.getPersonLoading());

            holder.tv_name.setText(value.author);
            holder.tv_time.setText(CommonUtil.formatTimeForListCommon(value.updatetime));


            if (!value.subject.equals("")) {
                holder.tv_title.setVisibility(View.VISIBLE);
                holder.tv_title.setText(CommonUtil.convetToHtml(
                        CommonUtil.parseEmoji(value.subject), mContext));
            } else {
                holder.tv_title.setVisibility(View.GONE);
            }

            if (!value.message.equals("")) {
                holder.tv_content.setVisibility(View.VISIBLE);
                holder.tv_content.setText(CommonUtil.convetToHtml(
                        CommonUtil.parseEmoji(value.message), mContext));
            } else {
                holder.tv_content.setVisibility(View.GONE);
            }



            if (Integer.parseInt(value.digest) > 0) {
                holder.iv_jing.setVisibility(View.VISIBLE);
            } else {
                holder.iv_jing.setVisibility(View.GONE);
            }

            if (value.recommendmy != null && value.recommendmy.equals("1")) {
                isZanMap.put(position, true);
                holder.iv_zan.setImageResource(R.drawable.icon_hand_frs_click);
            } else {
                isZanMap.put(position, false);
                holder.iv_zan.setImageResource(R.drawable.icon_hand_frs_normal);
            }

            if (value.forumname != null && value.forumname.length() != 0) {
                holder.tv_position.setText(value.forumname);
            }

            if (value.recommendarray != null && value.recommendarray.size() > 0) {
                holder.line.setVisibility(View.VISIBLE);
                holder.lay_zan.setVisibility(View.VISIBLE);
                if (value.recommendarray.size() >= 2) {
                    holder.tv_zanname1.setText(value.recommendarray.get(0).username + "、");
                    holder.tv_zanname2.setText(value.recommendarray.get(1).username);
                    holder.tv_zanguo.setText("等" + value.recommendtotal + "人赞过");
                } else {
                    holder.tv_zanname1.setText(value.recommendarray.get(0).username);
                    holder.tv_zanname2.setText("");
                    holder.tv_zanguo.setText("赞过");
                }
            } else {
                holder.line.setVisibility(View.GONE);
                holder.lay_zan.setVisibility(View.GONE);
            }


            // 视频或者图片
            if (holder.layout_imgs != null) {
                holder.layout_imgs.removeAllViews();
            }
            holder.layout_imgs.setVisibility(View.GONE);
            if (value.isvideo != null && value.isvideo.equals("1")) {
                holder.layout_imgs.setVisibility(View.VISIBLE);
                View sView = View.inflate(mContext, R.layout.image_pet_icon_shipinzuixin, null);
                ImageView iv = (ImageView) sView.findViewById(R.id.pet_icon);
                android.view.ViewGroup.LayoutParams lp1 = iv.getLayoutParams();
                TextView community_title = (TextView) sView.findViewById(R.id.community_title);
                lp1.width = (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                lp1.height = (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                iv.setScaleType(ScaleType.CENTER_CROP);
                iv.setLayoutParams(lp1);

                if (CommonParameter.isLoadImg) {
                    ImageLoader.getInstance().displayImage(value.videocover, iv);
                } else {
                    iv.setImageResource(R.drawable.picture_loading);
                }
                // community_title.setVisibility(View.VISIBLE);
                // community_title.setText(ParseMsgUtil.convetToHtml(
                // CommonUtil.parseEmoji(value.subject), mContext));
                LayoutParams lp =
                        new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                sView.setLayoutParams(lp);
                holder.layout_imgs.addView(sView);
            } else if (value.isvideo == null || value.isvideo.equals("0")) {
                if (value.pics.size() > 0) {
                    holder.layout_imgs.setVisibility(View.VISIBLE);
                }
                for (int i = 0; i < value.pics.size(); i++) {
                    final int j = i;
                    LinearLayout view1 =
                            (LinearLayout) View.inflate(mContext, R.layout.image_pet_icon_zuixin,
                                    null);
                    LinearLayout layout_count =
                            (LinearLayout) view1.findViewById(R.id.layout_for_count);
                    TextView tv_mycount = (TextView) view1.findViewById(R.id.tv_mycount);

                    ImageView iv1 = (ImageView) view1.findViewById(R.id.pet_icon);
                    android.view.ViewGroup.LayoutParams lp2 = iv1.getLayoutParams();

                    lp2.width =
                            (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                    lp2.height =
                            (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                    iv1.setScaleType(ScaleType.CENTER_CROP);
                    iv1.setLayoutParams(lp2);
                    if (CommonParameter.isLoadImg) {
                        ImageLoader.getInstance().displayImage(value.pics.get(i).url, iv1);
                    } else {
                        iv1.setImageResource(R.drawable.picture_loading);
                    }
                    LayoutParams lp3 =
                            new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                    if (i == 2 && Integer.parseInt(value.picnum) > 3) {
                        tv_mycount.setText("共" + value.picnum + "张");
                        layout_count.setVisibility(View.VISIBLE);
                    }


                    if (i > 0) {
                        lp3.leftMargin = CommonUtil.dip2px(mContext, 5);
                    }

                    view1.setLayoutParams(lp3);

                    view1.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO 到图片集
                            skipToImgs(j + "", value.tid);
                        }


                    });
                    holder.layout_imgs.addView(view1);

                }
            }



            final OnClickListener itemClickListener = new OnClickListener() {
                @Override
                public void onClick(View view) {
                    // TODO Auto-generated method stub
                    switch (view.getId()) {
                        case R.id.iv_icon:
                        case R.id.tv_name:
                        case R.id.tv_time:
                            // 进入他人中心
                            goOthersCenter(value.authorid, value.author, value.userface);
                            break;

                        case R.id.tv_zanname1:
                            // 进入该人中心
                            if (value.recommendarray != null && value.recommendarray.size() > 0) {
                                goOthersCenter(value.recommendarray.get(0).recommenduid,
                                        value.recommendarray.get(0).username,
                                        value.recommendarray.get(0).userface);
                            }
                            break;
                        case R.id.tv_zanname2:
                            // 进入该人中心
                            if (value.recommendarray != null && value.recommendarray.size() > 1) {
                                goOthersCenter(value.recommendarray.get(1).recommenduid,
                                        value.recommendarray.get(1).username,
                                        value.recommendarray.get(1).userface);
                            }
                            break;
                        case R.id.layout_gohuifu:
                            // 回复
                            // 进入展示图片切换
                            Toast.makeText(mContext, "进入回复!", Toast.LENGTH_SHORT).show();
                            break;
                        case R.id.layout_gozan:
                        case R.id.tv_zancount:
                        case R.id.iv_zan:
                            // 点赞
                            // goZan(position, value);

                            break;
                        case R.id.lay_zan:
                            // 进入点赞列表
                            Intent i = new Intent(mContext, ZanListActivity.class);
                            i.putExtra("title", value.subject);
                            i.putExtra("tid", value.tid);
                            i.putExtra("totalzan", Integer.parseInt(value.recommend_add));
                            mContext.startActivity(i);
                            break;

                        default:
                            break;
                    }

                }

                private void goOthersCenter(String uid, String name, String userface) {
                    // TODO Auto-generated method stub
                    // 进入他人中心
                    Intent intent =
                            new Intent(mContext, com.xindaoapp.happypet.activity.MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            UserInfoFragment.class.getCanonicalName());
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.KEY_UID, uid);
                    bundle.putString(Constants.KEY_USERNAME, name);
                    bundle.putString(Constants.KEY_USERFACE, userface);
                    intent.putExtra(Constants.KEY_BUNDLE, bundle);
                    mContext.startActivity(intent);
                }
            };

            OnClickListener videoClickListener = new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO 处理视频点击
                    Toast.makeText(mContext, "进入视频 !", Toast.LENGTH_SHORT).show();
                }
            };
            // 进入赞列表
            holder.lay_zan.setOnClickListener(itemClickListener);
            // 进入个人中心
            holder.iv_icon.setOnClickListener(itemClickListener);
            holder.tv_name.setOnClickListener(itemClickListener);
            holder.tv_time.setOnClickListener(itemClickListener);

            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent =
                            new Intent(mContext, com.xindaoapp.happypet.ui.PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, value.tid);
                    intent.putExtra(Constants.KEY_POST_FROM_POSTLIST, true);
                    mContext.startActivity(intent);
                }
            });

            return convertView;
        }

        protected void skipToImgs(String position, String tid) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(mContext, PostDetailImgsActivity.class);
            intent.putExtra(Constants.PARAM_PHOTO_POSITION, position);
            intent.putExtra(Constants.KEY_POST_TID, tid);
            mContext.startActivity(intent);
        }

        private void goZan(final int position, final MainZuixinData.MainTiezi value) {

            // TODO Auto-generated method stub
            if (UserState.isLogged((Activity) mContext)) {
                if (isZanMap.get(position)) {
                    Toast.makeText(mContext, "已赞过 !", Toast.LENGTH_SHORT).show();
                } else {
                    if (CommonUtil.checkNetState(mContext)) {

                        map.get(position).setImageResource(R.drawable.icon_hand_frs_click);


                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

                            final ObjectAnimator oa =
                                    ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)),
                                            "width",

                                            CommonUtil.dip2px(mContext, 0),
                                            CommonUtil.dip2px(mContext, 40));
                            final ObjectAnimator ob =
                                    ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)),
                                            "height",

                                            CommonUtil.dip2px(mContext, 0),
                                            CommonUtil.dip2px(mContext, 40));
                            oa.setInterpolator(new AccelerateDecelerateInterpolator());
                            ob.setInterpolator(new AccelerateDecelerateInterpolator());
                            oa.setDuration(250);
                            ob.setDuration(250);


                            final AnimatorSet set = new AnimatorSet();
                            set.play(oa).with(ob);

                            set.addListener(new AnimatorListener() {

                                @Override
                                public void onAnimationStart(Animator arg0) {
                                    // TODO Auto-generated method stub

                                }

                                @Override
                                public void onAnimationRepeat(Animator arg0) {
                                    // TODO Auto-generated method stub

                                }

                                @Override
                                public void onAnimationEnd(Animator arg0) {
                                    // TODO Auto-generated method stub


                                    ObjectAnimator oa2 =
                                            ObjectAnimator.ofInt(
                                                    new ViewWrapper2(map.get(position)), "width",
                                                    CommonUtil.dip2px(mContext, 40),
                                                    CommonUtil.dip2px(mContext, 25));
                                    ObjectAnimator ob2 =
                                            ObjectAnimator.ofInt(
                                                    new ViewWrapper2(map.get(position)), "height",
                                                    CommonUtil.dip2px(mContext, 40),
                                                    CommonUtil.dip2px(mContext, 25));
                                    oa2.setInterpolator(new AccelerateDecelerateInterpolator());
                                    ob2.setInterpolator(new AccelerateDecelerateInterpolator());
                                    oa2.setDuration(250);
                                    ob2.setDuration(250);

                                    AnimatorSet set2 = new AnimatorSet();
                                    set2.play(oa2).with(ob2);
                                    set2.start();

                                }

                                @Override
                                public void onAnimationCancel(Animator arg0) {
                                    // TODO Auto-generated method stub

                                }
                            });

                            set.start();
                        }


                        RequestParams params = new RequestParams();
                        params.put("tid", value.tid);
                        params.put("uid", UserState.getUserUid());
                        XDHttpClient.get(xdConfig.PRAISEPOST, params,
                                new AsyncHttpResponseHandler() {
                                    @Override
                                    public void onSuccess(int statusCode, String content) {

                                        try {
                                            if (new JSONObject(content).getInt("result") == 0) {

                                                MainZuixinData.MainTiezi.RecommendPerson info =
                                                        new MainZuixinData().new MainTiezi().new RecommendPerson();
                                                info.username = UserState.getUser().username;
                                                info.recommenduid = UserState.getUserUid();
                                                value.recommendarray.add(0, info);
                                                value.recommendmy = "1";
                                                value.recommend_add =
                                                        String.valueOf(Integer
                                                                .parseInt(value.recommend_add) + 1);
                                                isZanMap.put(position, true);
                                                Toast.makeText(mContext, "点赞成功", Toast.LENGTH_SHORT)
                                                        .show();
                                                notifyDataSetChanged();
                                            } else {
                                                map.get(position).setImageResource(
                                                        R.drawable.icon_hand_frs_normal);
                                                Toast.makeText(mContext, "点赞失败", Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        } catch (JSONException e1) {
                                            e1.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(Throwable arg0, String arg1) {
                                        super.onFailure(arg0, arg1);
                                        map.get(position).setImageResource(
                                                R.drawable.icon_hand_frs_normal);
                                        Toast.makeText(mContext, R.string.get_error_data,
                                                Toast.LENGTH_SHORT).show();
                                    }
                                });
                    } else {
                        Toast.makeText(mContext, R.string.pLease_check_network, Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }
                }
            }

        }



        private class ViewWrapper2 {
            private final View mTarget;

            public ViewWrapper2(View target) {
                mTarget = target;
            }

            public int getWidth() {
                return mTarget.getLayoutParams().width;
            }

            public void setWidth(int width) {
                mTarget.getLayoutParams().width = width;
                mTarget.requestLayout();
            }

            public int getHeight() {
                return mTarget.getLayoutParams().height;
            }

            public void setHeight(int height) {
                mTarget.getLayoutParams().height = height;
                mTarget.requestLayout();
            }
        }


        class ViewHolder {
            View line;
            LinearLayout layout_imgs;
            RelativeLayout lay_zan, layout_gozan, layout_gohuifu;
            CircleImageView iv_icon;
            ImageView iv_zan, iv_huifu, iv_jing;
            TextView tv_name, tv_time, tv_title, tv_content, tv_position, tv_views, tv_zancount,
                    tv_huifucount, tv_zanname1, tv_zanname2, tv_zanguo;
        }
    }

}
